//
//  UsbmuxdDevice.swift
//  PeerTalkPlaygroundWithSPM
//
//  Created by Cosmetic Cygia on 2024/10/12.
//

import Foundation
import PeerTalk

class UsbmuxdDevice: ObservableObject  {
    
    static let reconnectDelay: TimeInterval = 1.0
    
    static let notConnectedQueue = DispatchQueue(label: "jp.tret.PeerTalkPlaygroundWithSPM.notConnectedQueue")
    
    static let devicesModifyQueue = DispatchQueue(label: "devicesModifyThread")
    
    static let port: in_port_t = 50621
    
    var results:String = ""
    
    var channel: PTChannel?
    
    var deviceID: NSNumber = 0
    
    var connectedDeviceProperties: [String : Any] = [:]
    
    init(deviceID: NSNumber) {
        self.deviceID = deviceID
    }
    
    @Published var imageDir = URL(fileURLWithPath: "")
    @Published var formula = ""
    @Published var alias = ""
    @Published var volver:Bool = true
    
    func send(message: String) { //MARK: 发送给手机操作（USB）
        ELog.d(String(describing: type(of: self)),#function, self.deviceID.stringValue, #line)
        ELog.d(String(describing: type(of: self)),#function, message, #line)
        var _message = message
        let payload = _message.withUTF8 { buffer -> Data in
            var data = Data()
            data.append(CFSwapInt32HostToBig(UInt32(buffer.count)).data)
            data.append(buffer)
            return data
        }
        channel!.sendFrame(type: Settings.frameType, tag: PTFrameNoTag, payload: payload) { error in
            if let error = error {
                ELog.e(String(describing: type(of: self)), #function, "❌ Can not send the message - error: \(error) \"\(message)\"", #line)
                PavaoManager.instance.saveLog(logLevel: LOG_LEVEL.error, logContent: "❌ Can not send the message - error: \(error) \"\(message)\"")
            }
        }
    }
    
}
